//
//  OrderCommonCell.m
//  GasCome
//
//  Created by zfc on 2020/4/29.
//  Copyright © 2020 zfc. All rights reserved.
//

#import "OrderCommonCell.h"
#import "OrderProductCell.h"
@interface OrderCommonCell() <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UILabel *orderNumLab;
@property (nonatomic, strong) UILabel *statusLab;
@property (nonatomic, strong) UITableView *tableView;
//@property (nonatomic, strong) UIView *btnView;
@property (nonatomic, strong) UILabel *descLab;
@property (nonatomic, strong) UIButton *toPaybtn;
@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) UIButton *deleteBtn;
@property (nonatomic, strong) UIView *backView;
@property (nonatomic, strong)dispatch_source_t timer;

@end

@implementation OrderCommonCell

- (void)awakeFromNib {
    [super awakeFromNib];
}

- (void) setUI {
    self.backgroundColor = ColorF5;


    UIView *backView = [[UIView alloc] init];
    backView.backgroundColor = WhiteColor;
    backView.cornerRadius = 5;
    backView.clipsToBounds = YES;
    [self.contentView addSubview:backView];
    self.backView = backView;
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.contentView);
        make.leading.equalTo(self.contentView).offset(10);
        make.top.equalTo(self.contentView).offset(5);
    }];

    UIView *topView = [[UIView alloc] init];
    [backView addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.top.trailing.equalTo(backView);
        make.height.mas_equalTo(40);
    }];

    UILabel *orderNumLab = [[UILabel alloc] init];
    orderNumLab.text = @"订单编号:";
    orderNumLab.font = [UIFont systemFontOfSize:13 weight:UIFontWeightBold];
    orderNumLab.textColor = Color999;
    [topView addSubview:orderNumLab];
    self.orderNumLab = orderNumLab;
    [orderNumLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(topView);
        make.leading.equalTo(topView).mas_offset(15);
    }];

    UILabel *statusLab = [[UILabel alloc] init];
    statusLab.text = @"";
    statusLab.textColor = PriceColor;
    statusLab.font = [UIFont systemFontOfSize:12 weight:UIFontWeightMedium];
    [topView addSubview:statusLab];
    self.statusLab = statusLab;
    [statusLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(topView);
        make.trailing.equalTo(topView).mas_offset(-15);
    }];

//    UIView *btnView = [[UIView alloc] init];
//    [backView addSubview:btnView];
//    self.btnView = btnView;
//    [btnView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.leading.bottom.trailing.equalTo(backView);
//        make.height.mas_equalTo(60);
//    }];

    /*
    UIButton *toPaybtn = [UIButton buttonWithType:UIButtonTypeCustom];
    toPaybtn.cornerRadius = 14;
    toPaybtn.borderColor = PriceColor;
    toPaybtn.borderWidth = 1;
    [toPaybtn setTitle:@"去支付" forState:UIControlStateNormal];
    [toPaybtn setTitleColor:PriceColor forState:UIControlStateNormal];
    toPaybtn.titleLabel.font = [UIFont systemFontOfSize:13 weight:UIFontWeightMedium];
    toPaybtn.hidden = YES;
    [self.btnView addSubview:toPaybtn];
    self.toPaybtn = toPaybtn;
    [toPaybtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.btnView);
        make.trailing.equalTo(self.btnView).offset(-15);
        make.height.mas_equalTo(28);
    }];
    toPaybtn.block = ^(UIButton *sender) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(toPayWithOrder:)]) {
            [self.delegate toPayWithOrder:self.orderDic];
        }
    };

    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.cornerRadius = 14;
    cancelBtn.borderColor = ColorB3;
    cancelBtn.borderWidth = 1;
    [cancelBtn setTitle:@"取消订单" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:ColorB3 forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
    [self.btnView addSubview:cancelBtn];
    cancelBtn.hidden = YES;
    self.cancelBtn = cancelBtn;
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.btnView);
        make.trailing.equalTo(toPaybtn.mas_leading).offset(-10);
        make.height.mas_equalTo(28);
        make.width.mas_equalTo(80);
    }];
    cancelBtn.block = ^(UIButton *sender) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(cancelOrderWithOrder:)]) {
            [self.delegate cancelOrderWithOrder:self.orderDic];
        }
    };

    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.cornerRadius = 14;
    deleteBtn.borderColor = ColorB3;
    deleteBtn.borderWidth = 1;
    [deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
    [deleteBtn setTitleColor:ColorB3 forState:UIControlStateNormal];
    deleteBtn.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
    [self.btnView addSubview:deleteBtn];
    cancelBtn.hidden = YES;
    [deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.btnView);
        make.trailing.equalTo(self.btnView).offset(-10);
        make.height.mas_equalTo(28);
        make.width.mas_equalTo(80);
    }];
    self.deleteBtn = deleteBtn;
    deleteBtn.block = ^(UIButton *sender) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(deleteWithOrder:)]) {
            [self.delegate deleteWithOrder:self.orderDic];
        }
    };
*/

    [backView addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topView.mas_bottom);
        make.leading.trailing.equalTo(backView);
    }];


    UILabel *descLab = [[UILabel alloc] init];
    descLab.font = [UIFont systemFontOfSize:12 weight:UIFontWeightMedium];
    descLab.textColor = Color666;
    descLab.numberOfLines = 2;
    descLab.text = @"共0件商品 合计0元 (含运费0元)";
    descLab.textAlignment = NSTextAlignmentRight;
    self.descLab = descLab;
    [backView addSubview:descLab];
    [descLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(backView);
        make.leading.equalTo(backView).offset(10);
        make.top.equalTo(self.tableView.mas_bottom);
//        make.bottom.equalTo(self.btnView.mas_top);
        make.height.mas_equalTo(40);
    }];

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(orderDetailWithOrder:)]) {
            [self.delegate orderDetailWithOrder:self.orderDic];
        }
    }];
    [self addGestureRecognizer:tap];
}

- (void)setOrderDic:(NSDictionary *)orderDic {
    _orderDic = orderDic;
    NSArray *product = orderDic[@"product"];

    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(56*product.count);
    }];
    
    self.orderNumLab.text = [NSString stringWithFormat:@"订单编号:%@", self.orderDic[@"order_sn"]];
    [self configStatusLab];
    
    NSString *count = [NSString stringWithFormat:@"%zi", product.count];
    NSString *totalMoney = orderDic[@"pay_money"];
    NSString *ticketMoney = orderDic[@"ticket_money"];
    CGFloat freight = 0;
    CGFloat coupon_money = [orderDic[@"coupon_money"] floatValue];
    
    if ([orderDic[@"order_type"] integerValue] == 9) {
        for (NSDictionary *dic in orderDic[@"product"]) {
            freight += [dic[@"subjoin_delivery_money"] floatValue];
        }
    } else {
        freight = [orderDic[@"shipping_money"] floatValue];
    }
    
    if (freight == 0 && coupon_money == 0) {
        if ([ticketMoney floatValue] > 0) {
            self.descLab.text = [NSString stringWithFormat:@"(含气票抵扣%@元)\n共%@件商品合计%@元", ticketMoney, count, totalMoney];
        } else {
            self.descLab.text = [NSString stringWithFormat:@"共%@件商品合计%@元", count, totalMoney];
        }
    }
    
    if (freight > 0 && coupon_money == 0) {
        if ([ticketMoney floatValue] > 0) {
            self.descLab.text = [NSString stringWithFormat:@"(含运费%.2f元 气票抵扣%@元)\n共%@件商品合计%@元", freight, ticketMoney, count, totalMoney];
        } else {
            self.descLab.text = [NSString stringWithFormat:@"(含运费%.2f元)\n共%@件商品合计%@元", freight, count, totalMoney];

        }
    }
    
    if (freight == 0 && coupon_money > 0) {
        if ([ticketMoney floatValue] > 0) {
            self.descLab.text = [NSString stringWithFormat:@"(含优惠券-%.2f元 气票抵扣%@元)\n共%@件商品合计%@元", coupon_money, ticketMoney, count, totalMoney];
        } else {
            self.descLab.text = [NSString stringWithFormat:@"(含优惠券-%.2f元)\n共%@件商品合计%@元", coupon_money, count, totalMoney];
        }
    }
    
    if (freight > 0 && coupon_money > 0) {
        if ([ticketMoney floatValue] > 0) {
            self.descLab.text = [NSString stringWithFormat:@"(含运费%.2f元 优惠券-%.2f元  气票抵扣%@元)\n共%@件商品合计%@元", freight, coupon_money, ticketMoney, count, totalMoney];
        } else {
            self.descLab.text = [NSString stringWithFormat:@"(含运费%.2f元 优惠券-%.2f元)\n共%@件商品合计%@元", freight, coupon_money, count, totalMoney];
        }
    }
    

//    if ([orderDic[@"shipping_money"] floatValue] > 0) {
//        self.descLab.text = [NSString stringWithFormat:@"共%lu件商品合计%@元(含运费%@元)\n", (unsigned long)product.count ,orderDic[@"pay_money"], orderDic[@"shipping_money"]];
//    } else {
//        self.descLab.text = [NSString stringWithFormat:@"共%lu件商品合计%@元\n",(unsigned long)product.count, orderDic[@"pay_money"]];
//    }

    [self.tableView reloadData];
    
//    [self createBtnView];
    
    

    
}

- (void) createBtnView {
    NSInteger orderStatus = [self.orderDic[@"order_status"] integerValue];

//    if (orderStatus == 0 || orderStatus == -4) {
//        self.btnView.hidden = NO;
//    } else {
//        self.btnView.hidden = YES;
//    }



    /*
    UIButton *refundBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    refundBtn.cornerRadius = 14;
    refundBtn.borderColor = gcBackGroundColorB3;
    refundBtn.borderWidth = 1;
    [refundBtn setTitle:@"退款" forState:UIControlStateNormal];
    [refundBtn setTitleColor:gcBackGroundColorB3 forState:UIControlStateNormal];
    refundBtn.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
    [self.btnView addSubview:refundBtn];
    refundBtn.hidden = YES;
    [refundBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.btnView);
        make.trailing.equalTo(toPaybtn.mas_leading).offset(-10);
        make.height.mas_equalTo(28);
        make.width.mas_equalTo(80);
    }];
    refundBtn.block = ^(UIButton *sender) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(refundWithOrder:)]) {
            [self.delegate refundWithOrder:self.orderDic];
        }
    };*/




    if (orderStatus == 0) { //待付款  btn:取消订单 去支付
        self.toPaybtn.hidden = NO;
        self.cancelBtn.hidden = NO;
        self.deleteBtn.hidden = YES;
    }

    if (orderStatus == -4) { //订单关闭 btn:删除
        self.toPaybtn.hidden = YES;
        self.cancelBtn.hidden = YES;
        self.deleteBtn.hidden = NO;
    }


}

- (void) configStatusLab {
    NSString *status = @"";
    NSInteger orderType = [self.orderDic[@"order_type"] integerValue];
    NSInteger orderStatus = [self.orderDic[@"order_status"] integerValue];

    switch (orderStatus) {
        case 0:
            status = @"待付款";
            break;
        case 1:
            if (orderType == 9) {
                status = @"待接单";
            } else {
                status = @"待发货";
            }
            break;
        case 2:
            status = @"已发货";
            break;
        case 3:
            status = @"已收货";

            break;
        case 4:
            status = @"已完成";

            break;
        case -1:
            status = @"申请退款";
            break;
        case -2:
            status = @"退款中";
            break;
        case -3:
            status = @"退款完成";
            break;
        case -4:
            status = @"已关闭";
            break;
        case -5:
            status = @"撤销申请";
            break;
        case 101:
            status = @"待成团";
            break;
        case 104:
            status = @"待分配";
            break;
        case 105:
            status = @"待接单";
            break;
        case 106:
            status = @"待配送";
            break;
        default:
            break;
    }

    self.statusLab.text = status;

    if (self.timer) {
        dispatch_source_cancel(_timer);
    }

    
    NSInteger time = [self.orderDic[@"close_time"] integerValue] - [[NSDate date] timeIntervalSince1970];
    if (time > 0) {
        [self setTheCountdownWithStartWithTime:time+1];
    }

}


- (void)setTheCountdownWithStartWithTime:(NSInteger)timeLine {
    //倒计时时间
    NSInteger endTime = [[NSDate date] timeIntervalSince1970] + timeLine;


    dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0, queue);
    //每秒执行一次
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL,0), 1.0 * NSEC_PER_SEC,0);
    dispatch_source_set_event_handler(_timer, ^{
        NSInteger currentTIme = [[NSDate date] timeIntervalSince1970];

        //倒计时结束，关闭
        if (endTime <= currentTIme) {
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
//                [self.toPaybtn setTitle:@"去支付" forState:UIControlStateNormal];
            });
            
            if (self.delegate && [self.delegate respondsToSelector:@selector(reloadList)]) {
                [self.delegate reloadList];
            }
        } else {

            dispatch_async(dispatch_get_main_queue(), ^{
                [self setDesc1Lab111WithTime:endTime-currentTIme];
            });
        }
    });
    dispatch_resume(_timer);
}

- (void) setDesc1Lab111WithTime:(NSInteger) time {

    if (time < 0) {
        [self.toPaybtn setTitle:@"去支付" forState:UIControlStateNormal];
    } else {
        NSString *timeStr = [NSString stringWithFormat:@"去支付(%02zi:%02zi)", time/60, time%60];

        CGFloat w = [Untils getWidthWithText:timeStr height:28 font:13];
//        CGFloat w = [Untils getLabelWidthWithText:timeStr height:28 font:[UIFont systemFontOfSize:13 weight:UIFontWeightMedium]];
        [self.toPaybtn setTitle:timeStr forState:UIControlStateNormal];
        [self.toPaybtn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(w+20.f);
        }];
    }
}



- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.scrollEnabled = NO;
        [_tableView registerClass:[OrderProductCell class] forCellReuseIdentifier:@"OrderProductCell"];
    }
    return _tableView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *product = self.orderDic[@"product"];
    return product.count;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *product = self.orderDic[@"product"];
    NSDictionary *productDic = product[indexPath.row];
    OrderProductCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderProductCell" forIndexPath:indexPath];
    cell.productDic = productDic;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 56;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}


- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

}

@end
